<template>
	<div class="CreationArea">
		<HeaderTab>
			<div slot="left">
				<router-link to="/original" class="glyphicon glyphicon-menu-left return_but"></router-link>
			</div>
			<div slot="center" class="CreationArea_header_center">
				创作专区
			</div>
		</HeaderTab>
		<form class="form-horizontal" action="" method="">
			<div class="CreationArea_essential_information">
				<h4>基本信息</h4>
				<div class="CreationArea_form">
					<div class="form-group">
						<label class="col-sm-2 control-label">作品标题</label>
						<div class="col-sm-10">
							<input type="text" class="form-control" id="inputTitle3" placeholder="请输入您的作品标题">
						</div>
					</div>
					<div class="form-group">
						<label class="col-sm-2 control-label">作者</label>
						<div class="col-sm-10">
							<input type="text" class="form-control" id="inputUsername3" :value="user_name" :placeholder="user_name" disabled>
						</div>
					</div>
					<div class="form-group">
						<label class="col-sm-2 control-label">选择发布专区:</label>
						<div class="CreationArea_radio_box" id="inlineRadio">
							<label class="radio-inline">
								<input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="热门" checked>热门
							</label>
							<label class="radio-inline">
								<input type="radio" name="inlineRadioOptions" id="inlineRadio2" value="精选">精选
							</label>
							<label class="radio-inline">
								<input type="radio" name="inlineRadioOptions" id="inlineRadio3" value="推荐">推荐
							</label>
						</div>
					</div>
					<div class="form-group">
						<label class="col-sm-2 control-label">选择作品类型:</label>
						<div class="col-sm-10">
							<select id="citySel" class="form-control">
								<option name="optionitem" v-for="t in tag_arr">{{t.tag_name}}</option>
							</select>
						</div>
					</div>
					<div class="form-group">
						<label class="col-sm-2 control-label">书籍简介</label>
						<div class="col-sm-10">
							<textarea id="introduction_text" class="form-control" rows="5" placeholder="请为你的作品填写对应的简介信息"></textarea>
						</div>
					</div>
				</div>
			</div>
			<div class="CreationArea_chapter_box">
				<h4>章节详情</h4>
				<div class="CreationArea_chapter_options">
					<div class="chapter_options" v-for="(v, k) in chapter_itemdata" :key="k">
						<div class="form-group">
							<label class="col-sm-2 control-label">章节名称</label>
							<div class="col-sm-10">
								<input type="text" class="form-control" id="inputEmail3" placeholder="本章节名称" v-model="v.chapter_name" disabled>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">上传本章节文件</label>
							<input type="file" class="exampleInputFile" name="file">
							<div class="input-group upload_butBox">
								<span class="input-group-btn">
									<button @click="upload($event)" class="btn btn-default upload_but" type="button">上传</button>
								</span>
								<input type="text" class="form-control upload_path" placeholder="地址返回" v-model="v.chapter_file">
							</div>
						</div>
						<div class="CreationArea_chapter_delbox">
							<button class="del_chapterBut" @click.prevent="del(k)">删除章节</button>
						</div>
					</div>
				</div>
				<div class="CreationArea_chapter_addbox">
					<button @click.prevent="add()">添加章节</button>
				</div>
			</div>
			<div class="chapter_submit_butbox">
				<button type="button" class="btn btn-default sub_style" @click="uploadAllData()">上传作品</button>
			</div>
		</form>
		<div class="mask" v-if="bol" @click="close">
			<div class="box" @click.stop="">
				<h1 class="glyphicon glyphicon-ok"></h1>
				<p class="mask_tip">{{mask_tip}}</p>
			</div>
		</div>
		<div class="merk" v-if="bel" @click="clese">
			<div class="bex" @click.stop="">
				<h1 class="glyphicon glyphicon-remove"></h1>
				<p class="merk_tip">{{merk_tip}}</p>
			</div>
		</div>
	</div>
</template>

<script>
	import $ from 'jquery';
	import HeaderTab from 'common/HeaderTab/HeaderTab.vue'

	export default {
		name: 'CreationArea',
		components: {
			HeaderTab
		},
		data() {
			return {
				bol: false,
				bel: false,
				mask_tip: '',
				j: 0,
				tag_arr: [],
				user_name: '',
				chapter_itemdata: [{
					chapter_name: '',
					chapter_file: ''
				}],
				bodyBgImage: 'url(' + require('../../../assets/img/backgroud_img/003.jpg') + ') repeat fixed'
			}
		},
		methods: {
			// 添加章节按钮实现
			add() {
				var field = {
					chapter_name: '',
					chapter_file: ''
				}
				this.chapter_itemdata.push(field);
			},

			// 删除章节按钮实现
			del(k) {
				this.chapter_itemdata.splice(k, 1);
				this.j--
			},

			// 添加背景图片
			setBodyBackGround() {
				document.body.style.backgroundSize = '100%'
				document.body.style.background = this.bodyBgImage
			},

			// 清除背景图
			clearBodyBackGround() {
				document.body.style.backgroundImage = ''
			},

			// 加载标签
			loadTag() {
				this.axios.get('http://192.168.43.169/api/booktag').then((response) => {
					this.tag_arr = response.data.data;
				});
			},

			// 加载用户姓名
			loadUser() {
				this.axios.get('http://192.168.43.169/api/userquery/' + this.$store.state.userid).then((response) => {
					this.user_name = response.data.data[0].username;
				});
			},

			//获取上传通行证
			getOssToken() {
				var _self = this;
				this.axios.get('http://192.168.43.169/aliyun/sign').then((res) => {
					var data = res.data;
					if (data.code == 0) {
						_self.aliyunOssToken = data.data;
					} else {
						_self.$message.warning(data.msg);
					}
				});
			},

			// 文件上传实现
			upload(event) {
				var _self = this;
				var getSuffix = function(fileName) {
					var pos = fileName.lastIndexOf(".");
					var suffix = '';
					if (pos != -1) {
						suffix = fileName.substring(pos);
					}
					return suffix;
				}

				let el = event.currentTarget;
				var file = el.parentNode.parentNode.parentNode.childNodes[1].value;
				if (file.length == 0) {
					alert("请选择文件");
				}

				var oFileName = file.lastIndexOf('\\');
				var oFileName = file.substr(oFileName + 1);
				var fileName = oFileName.lastIndexOf('.');
				var fileName = oFileName.substr(0, fileName);

				let real_filename = fileName
				console.log(fileName);

				var filename = new Date().getTime() + getSuffix(file);
				var formData = new FormData();

				//注意formData里append添加的键的大小写
				formData.append('key', _self.aliyunOssToken.dir + real_filename); //存储在oss的文件路径
				formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
				formData.append('policy', _self.aliyunOssToken.policy); //policy
				formData.append('Signature', _self.aliyunOssToken.signature); //签名
				formData.append("file", $(".exampleInputFile")[0].files[0]);
				formData.append('success_action_status', 200); //成功后返回的操作码


				var url = _self.aliyunOssToken.host;
				var fileUrl = _self.aliyunOssToken.cdn_host + '/' + _self.aliyunOssToken.dir + real_filename;
				var dop = {
					chapter_name: '',
					chapter_file: ''
				};
				$.ajax({
					url: url,
					type: 'POST',
					data: formData,
					// async: false,
					cache: false,
					contentType: false,
					processData: false,
					success: function(data) {
						el.parentNode.parentNode.childNodes[1].value = fileUrl
						dop.chapter_name = real_filename;
						dop.chapter_file = fileUrl;
						_self.chapter_itemdata.splice(_self.j, 1, dop);
						_self.j++
						console.log(fileUrl);
						console.log(data);
					},
					error: function(data) {
						console.log(data);
					}
				});
			},

			// 把用户填写的信息一次过全部提交到后台
			uploadAllData() {
				let text1 = document.getElementById('inputTitle3').value
				let text2 = document.getElementById('inputUsername3').value
				let text3 = $('#inlineRadio').find('input[name="inlineRadioOptions"]:checked').val()
				let text4 = $('#citySel').find('option[name="optionitem"]:checked').val()
				let text5 = document.getElementById('introduction_text').value

				// （1）axios1,把上传作品保存出去
				// 验证必填字段是否为空
				if (text1 && text5) {
					this.axios.get('http://192.168.43.169/api/uploadOriginalBook', {
						params: {
							book_name: text1,
							author: text2,
							special_area: text3,
							book_type: text4,
							introduce: text5,
						},
					}).then((response) => {
						let book_id = response.data;
						// （2）把对应作品id的章节保存进去
						for (let i = 0; i < this.chapter_itemdata.length; i++) {
							this.chapter_itemdata[i]
							this.axios.get('http://192.168.43.169/api/uploadOriginalChapter', {
								params: {
									chapter_title: this.chapter_itemdata[i].chapter_name,
									chapter_path: this.chapter_itemdata[i].chapter_file,
									book_id: book_id,
								},
							}).then((response) => {
								let _self = this
								_self.bol = true
								_self.mask_tip = response.data
								// 设置一定时间后关闭提醒框
								setTimeout(function() {
									_self.$router.push('/original');
									setTimeout(function() {
										_self.bol = false;
									}, 1000);
								}, 2000);
							});
						}
					});
				} else {
					let _self = this
					_self.bel = true
					_self.merk_tip = "上传字段不可为空！！"
					// 设置一定时间后关闭提醒框
					if (_self.bel) {
						setTimeout(function() {
							_self.bel = false
						}, 2000);
					}
				}
			},

			// 模态框关闭事件
			close() {
				this.bol = !this.bol;
			},

			// 模态框关闭事件
			clese() {
				this.bel = !this.bel;
			}
		},
		mounted() {
			// 进来的时候调用添加
			this.setBodyBackGround();
			this.getOssToken();
		},
		beforeDestroy() {
			// 离开页面的时候清除
			this.clearBodyBackGround()
		},
		created() {
			this.loadTag();
			this.loadUser();
		}
	}
</script>

<style>
	@import '~assets/css/CreationArea.css';
	@import '~assets/css/mask.css';
</style>
